package com.squeekeek.util.qrcode;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final int CAPTURE_IMAGE = 200;
	private ImageView imgPreviewFrame;
	private ProgressDialog progressBar;
	private Button decodeBtn;
	
	private BaseLoaderCallback OpenCVCallbackh = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch(status) {
				case LoaderCallbackInterface.SUCCESS:
					Log.d("Main", "OpenCV Loaded Successfully!");
					break;
				default:
					super.onManagerConnected(status);
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Button captureBtn;
		
		super.onCreate(savedInstanceState);
		
		if(OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, OpenCVCallbackh)) {
			setContentView(R.layout.activity_main);
			
			captureBtn = (Button) findViewById(R.id.btn_start);
			imgPreviewFrame = (ImageView) findViewById(R.id.frame_imgpreview);
			
			captureBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					openCameraApp();
				}
			});
			
			decodeBtn = (Button) findViewById(R.id.btn_decode);
		}
		else {
			Log.d("Main", "Cannot connect to OpenCV Manager");
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int reqCode, int resCode, Intent intent) {
		final String imgFileName;
		
		final Button captureBtn;
		Bitmap imgBitmap;
		LayoutParams captureBtnParams;
		
		captureBtn = (Button) findViewById(R.id.btn_start);
		decodeBtn = (Button) findViewById(R.id.btn_decode);
		
		captureBtnParams = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		
		if(reqCode == CAPTURE_IMAGE) {
			if(resCode == RESULT_OK) {
				imgFileName = intent.getStringExtra(GetQRPhoto.TAG_IMGLOC);
				
				Log.d("QRCode", "Image saved at " + imgFileName);
				
				imgBitmap = BitmapFactory.decodeFile(imgFileName);
				
				imgPreviewFrame.setImageBitmap(imgBitmap);
				
				captureBtnParams.addRule(RelativeLayout.ALIGN_RIGHT, RelativeLayout.TRUE);
				captureBtnParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
				captureBtn.setLayoutParams(captureBtnParams);
				
				decodeBtn.setText(R.string.actstr_decodebtn);
				decodeBtn.setOnClickListener(null);
				decodeBtn.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						QrDecodeTask myTask;
						
						try {
							progressBar = new ProgressDialog(v.getContext());
							progressBar.setCancelable(false);
							progressBar.setMessage("Decoding QR Code");
							progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
							progressBar.setIndeterminate(true);
							progressBar.show();
							
							myTask = new QrDecodeTask();
							myTask.execute(new String[] {imgFileName});
						
							decodeBtn.setText(R.string.actstr_infobtn);
						}
						catch(Exception e) {
							Toast.makeText(v.getContext(), "Exception in main thread: " + e.getMessage(), Toast.LENGTH_LONG).show();
							Log.d("QRCode", "Exception in main thread: " + e.getMessage());
						}
					}
					
				});
				decodeBtn.setVisibility(View.VISIBLE);
			}
			else if(resCode == RESULT_CANCELED) {
				decodeBtn.setVisibility(View.GONE);
				
				captureBtnParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
				captureBtnParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
				captureBtn.setLayoutParams(captureBtnParams);
				
				Toast.makeText(this, "Image capture cancelled", Toast.LENGTH_LONG).show();
				//Log.d("QRCode", "Image capture cancelled");
			}
		}
	}
	
	public void openCameraApp() {
		Intent intent;
		
		intent = new Intent(this, GetQRPhoto.class);
		startActivityForResult(intent, CAPTURE_IMAGE);
	}
	
	private class QrDecodeTask extends AsyncTask <String, Void, QRAlgorithm> {

		@Override
		protected QRAlgorithm doInBackground(String... imgPaths) {
			QRAlgorithm qrCode = null;
			
			try {
				qrCode = new QRAlgorithm(imgPaths[0]);
				qrCode.localThreshBernsen();
				qrCode.getFinderPatterns();
				qrCode.setOrientation();
			}
			catch(Exception e) {
				Log.d("QRCode", "Error in decoding QR Code: " + e.getMessage());
			}
			
			return qrCode;
		}
		
		@Override
		protected void onPostExecute(final QRAlgorithm qrCode) {
			Bitmap imgOut;
			
			try {
				imgOut = BitmapFactory.decodeFile(qrCode.saveThreshImg());
				imgPreviewFrame.setImageBitmap(imgOut);
				
				decodeBtn.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						AlertDialog.Builder alertDiag;
						String myMsg;
						
						myMsg = qrCode.dumpData();
						
						if(myMsg != null) {
							alertDiag = new AlertDialog.Builder(v.getContext());
							alertDiag.setMessage(myMsg);
							
							alertDiag.setPositiveButton("Close", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface diag, int myBtn) {
									// TODO Auto-generated method stub
									
								}
							});
							
							alertDiag.show();
						}
						else {
							Toast.makeText(v.getContext(), "Nothing to display.", Toast.LENGTH_LONG).show();
						}
					}
					
				});
				
				progressBar.dismiss();
			}
			catch(Exception e) {
				Log.d("QRCode", "Error in decoding QR Code: " + e.getMessage());
			}
		}
		
	}
}
